﻿Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO
Imports System.IO.IsolatedStorage
Imports System.Windows.Media
Imports System.Windows.Media.Imaging
Imports System.Data.SqlTypes
Imports System.Reflection

Namespace CoverFlow
    Public Class ThumbnailManager
        Implements IThumbnailManager
#Region "Fields"
        Private ReadOnly store As IsolatedStorageFile
#End Region
       
        Private Function GetThumbnail(path As Byte()) As Byte()
            Dim Stream As New MemoryStream(path)
            Dim source As Image = Image.FromStream(Stream)

            Stream.Close()

            Dim height As Integer = 300 'source.Height
            Dim width As Integer = 310 'source.Width
            Dim factor As Integer = (height - 1) \ 250 + 1
            Dim smallHeight As Integer = height \ factor
            Dim smallWidth As Integer = width \ factor

            Dim thumb As Image = source.GetThumbnailImage(smallWidth, smallHeight, Nothing, IntPtr.Zero)

            Using ms = New MemoryStream()
                thumb.Save(ms, ImageFormat.Png)
                ms.Flush()
                ms.Seek(0, SeekOrigin.Begin)
                Dim result = New Byte(ms.Length - 1) {}
                ms.Read(result, 0, CInt(ms.Length))
                Return result
            End Using
        End Function
        Public Sub New()
            store = IsolatedStorageFile.GetUserStoreForAssembly()
        End Sub
        Public Function GetThumbnail(host As String, path__1 As SqlBinary) As ImageSource Implements IThumbnailManager.GetThumbnail
            Dim thumbName As String = host & ".png"

            If store.GetFileNames(thumbName).Length = 0 Then
                Using stream = New IsolatedStorageFileStream(thumbName, FileMode.CreateNew, store)
                    Dim data As Byte() = GetThumbnail(path__1) ' CAMBIAR ESTO PARA LA BD
                    stream.Write(data, 0, data.Length)
                End Using
            End If

            Using stream = New IsolatedStorageFileStream(thumbName, FileMode.Open, store)
                Dim image = New BitmapImage()
                image.BeginInit()
                image.CacheOption = BitmapCacheOption.OnLoad
                image.StreamSource = stream
                image.EndInit()
                image.Freeze()

                Return image
            End Using
        End Function
        Public Sub RemoveIsolated()
            Try
                store.Remove()
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
            End Try
        End Sub
    End Class
End Namespace
